package testes.vSys.action;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import testes.vSys.Constants;
import testes.vSys.bean.Brand;
import testes.vSys.bean.Color;
import testes.vSys.bean.Fuel;
import testes.vSys.bean.Location;
import testes.vSys.bean.Model;
import testes.vSys.bean.Vehicle;
import testes.vSys.dao.DAOFactory;
import testes.vSys.dao.IModelDao;
import testes.vSys.dao.IVehicleDao;
import testes.vSys.form.VehicleForm;
import testes.vSys.util.Utilities;
import testes.vSys.util.ValidationErrorsTag;

public class VehicleAction extends DispatchAction {

	private final String VEHICLES_COLLECTION = "vehiclesCollection";
	private final String FUELS_COLLECTION = "fuelsCollection";
	private final String COLORS_COLLECTION = "colorsCollection";
	private final String BRANDS_COLLECTION = "brandsCollection";
	private final String MODELS_COLLECTION = "modelsCollection";


	public ActionForward load(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		VehicleForm vehicleForm = (VehicleForm)form;
	
		IVehicleDao vehicleDAO = DAOFactory.getVehicleDao();
		
		IModelDao modelDAO = DAOFactory.getModelDao();
		
		Collection<Vehicle> vehicles = vehicleDAO.getVehicles();
		Collection<Color> colors = vehicleDAO.getAvaiableColors();
		Collection<Fuel> fuels = vehicleDAO.getAvaiableFuels();
		Collection<Brand> brands = modelDAO.getAvaiableBrands();
		
		request.setAttribute(VEHICLES_COLLECTION, vehicles);
		request.setAttribute(FUELS_COLLECTION, fuels);
		request.setAttribute(COLORS_COLLECTION, colors);
		request.setAttribute(BRANDS_COLLECTION, brands);
		request.setAttribute("testesCollection", new ArrayList<Vehicle>());

		
		Collection<Model> models = new ArrayList<Model>();
		Brand brand = null; 
		if (Utilities.validateNumeric(vehicleForm.getSelectedBrand()))
			brand = modelDAO.getBrandById(Integer.valueOf(vehicleForm.getSelectedBrand()));
		else
			brand = brands.iterator().next();

		models = modelDAO.getModelsByBrand(brand);
		vehicleForm.setSelectedBrand(String.valueOf(brand.getId()));
		request.setAttribute(MODELS_COLLECTION, models);
		
		return mapping.findForward("vehicle");
	}

	
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		VehicleForm vehicleForm = (VehicleForm)form;
		
		Collection<String> errors = validateForm(vehicleForm);
		if (errors != null){
			request.getSession().setAttribute(ValidationErrorsTag.VALIDATION_ERRORS, errors);
			return load(mapping, form, request, response);
		}
		
		Vehicle vehicle = formToBean(Integer.parseInt(vehicleForm.getVehicleId()),vehicleForm); 

		DAOFactory.getVehicleDao().updateVehicle(vehicle);
		vehicleForm.resetForm();
		
		return load(mapping, form, request, response);
	}

	
	public ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		VehicleForm vehicleForm = (VehicleForm)form;
		
		Collection<String> errors = validateForm(vehicleForm);
		if (errors != null){
			request.getSession().setAttribute(ValidationErrorsTag.VALIDATION_ERRORS, errors);
			System.out.println("ao inserir -> "+errors);
			return load(mapping, form, request, response);
		}
		
		Vehicle vehicle = formToBean(vehicleForm);
		
		DAOFactory.getVehicleDao().createVehicle(vehicle);

		if (vehicle.getId() == Constants.VSYS_UNKNOWN_ID){
			errors = new ArrayList<String>();
			errors.add(Utilities.getMessage("vehicle.error.notpossible"));
			request.getSession().setAttribute(ValidationErrorsTag.VALIDATION_ERRORS, errors);
			return load(mapping, form, request, response);
		}
		

		vehicleForm.resetForm();
		
		return load(mapping, form, request, response);
	}

	public ActionForward changeToEditMode(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		VehicleForm vehicleForm = (VehicleForm)form;
		int vehicleId = Integer.parseInt(vehicleForm.getVehicleId());
		
		Vehicle vehicle = DAOFactory.getVehicleDao().getVehicleById(vehicleId);
		beanToForm(vehicle, vehicleForm);
		
		return load(mapping, form, request, response);
	}

	public ActionForward remove(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		VehicleForm vehicleForm = (VehicleForm)form;
		int vehicleId = Integer.parseInt(vehicleForm.getVehicleId());
		
		DAOFactory.getVehicleDao().removeVehicle(vehicleId);
		vehicleForm.resetForm();
		
		return load(mapping, form, request, response);
	}

	public ActionForward changeModel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		return load(mapping, form, request, response);
	}
	
	public ActionForward clearFields(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		VehicleForm vehicleForm = (VehicleForm)form;
		vehicleForm.resetForm();
		
		return load(mapping, form, request, response);
	}
	
	private Vehicle formToBean(int id,VehicleForm vehicleForm){

		Vehicle vehicle = new Vehicle(id);
		
		vehicle.setPlate(vehicleForm.getPlate());
		vehicle.setYear(Integer.parseInt(vehicleForm.getYear()));
		vehicle.setValue(Float.parseFloat(vehicleForm.getValue()));
		vehicle.setLocation(new Location(vehicleForm.getCity(),vehicleForm.getState()));
		vehicle.setModel(DAOFactory.getModelDao().getModelById(Integer.parseInt(vehicleForm.getSelectedModel())));
		vehicle.setFuel(DAOFactory.getVehicleDao().getFuelById(Integer.parseInt(vehicleForm.getSelectedFuel())));
		vehicle.setColor(DAOFactory.getVehicleDao().getColorById(Integer.parseInt(vehicleForm.getSelectedColor())));

		return vehicle;
	}
	
	private Vehicle formToBean(VehicleForm vehicleForm){
		return formToBean(Constants.VSYS_UNKNOWN_ID,vehicleForm);
	}
	
	
	private void beanToForm(Vehicle vehicle, VehicleForm vehicleForm){
		
		vehicleForm.setVehicleId(String.valueOf(vehicle.getId()));
		vehicleForm.setPlate(vehicle.getPlate());
		vehicleForm.setYear(String.valueOf(vehicle.getYear()));

		
		vehicleForm.setValue(String.valueOf(vehicle.getValue()));
		
		
		vehicleForm.setCity(vehicle.getLocation().getCity());
		vehicleForm.setState(vehicle.getLocation().getState());
		vehicleForm.setSelectedBrand(String.valueOf(vehicle.getModel().getBrand().getId()));
		vehicleForm.setSelectedModel(String.valueOf(vehicle.getModel().getId()));
		vehicleForm.setSelectedFuel(String.valueOf(vehicle.getFuel().getId()));
		vehicleForm.setSelectedColor(String.valueOf(vehicle.getColor().getId()));

	}
	
	private Collection<String> validateForm(VehicleForm vehicleForm){

		Collection<String> errors = new ArrayList<String>();
		

		if (!Utilities.validateRequired(vehicleForm.getPlate()))
			errors.add(Utilities.getMessage("vehicle.error.required",Utilities.getMessage("vehicle.labels.plate")));
		
		if (!Utilities.validateRequired(vehicleForm.getYear()))
			errors.add(Utilities.getMessage("vehicle.error.required",Utilities.getMessage("vehicle.labels.year")));

		if (!Utilities.validateRequired(vehicleForm.getValue()))
			errors.add(Utilities.getMessage("vehicle.error.required",Utilities.getMessage("vehicle.labels.value")));

		if (!Utilities.validateRequired(vehicleForm.getCity()))
			errors.add(Utilities.getMessage("vehicle.error.required",Utilities.getMessage("vehicle.labels.city")));

		if (!Utilities.validateRequired(vehicleForm.getState()))
			errors.add(Utilities.getMessage("vehicle.error.required",Utilities.getMessage("vehicle.labels.state")));

		if (!Utilities.validateNumeric(vehicleForm.getYear()))
			errors.add(Utilities.getMessage("vehicle.error.invalid",Utilities.getMessage("vehicle.labels.year")));

		if (!Utilities.validateReal(vehicleForm.getValue()))
			errors.add(Utilities.getMessage("vehicle.error.invalid",Utilities.getMessage("vehicle.labels.value")));

		// retorna a collection caso tenha algum erro, null caso contr�rio 
		return (errors.size() > 0) ? errors : null;
	}
}
